<template>
  <div class="view-container">
    <el-input class="search" v-model="keyword">
      <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
    </el-input>
    <div id="qqmap"></div>
  </div>
</template>

<script>
import * as qqmap from '@/utils/qqmap'
export default {
  data() {
    return {
      keyword: '沙嘴',
      map: null,
      markers: []
    }
  },
  methods: {
    _clearMarkers() {
      let marker
      while ((marker = this.markers.pop())) {
        marker.setMap(null)
      }
      this.markers = []
    },
    _createMarker(poi, icon) {
      const markerOption = {
        map: this.map,
        title: poi.name,
        position: poi.latLng,
        icon
      }
      return new qq.maps.Marker(markerOption)
    },
    search() {
      this._clearMarkers()
      qqmap
        .search('深圳', this.keyword)
        .then(res => {
          console.log(res)

          const pois = res.detail.pois

          const centerLatLng = pois[0].latLng
          const center = new qq.maps.LatLng(centerLatLng.lat, centerLatLng.lng)
          this.map = new qq.maps.Map(document.getElementById('qqmap'), {
            center,
            zoom: 13
          })

          const latlngBounds = new qq.maps.LatLngBounds()
          pois.forEach((poi, index) => {
            latlngBounds.extend(poi.latLng)
            const markerIcon =
              index === 0
                ? 'https://www.easyicon.net/api/resizeApi.php?id=1175814&size=32'
                : ''
            const marker = this._createMarker(poi, markerIcon)
            this.markers.push(marker)

            qq.maps.event.addListener(marker, 'click', () => {
              console.log(poi)
            })
          })

          this.map.fitBounds(latlngBounds)
        })
        .catch(e => {
          console.log(e)
        })
    }
  },
  mounted() {
    this.search()
  }
}
</script>

<style lang="stylus" scoped>
.view-container
  display flex
  flex-direction column
  height 100%
  .search
    margin-bottom 20px
  #qqmap
    width 100%
    flex 1
</style>
